<template>

  <!-- 搜索工作栏 -->
  <ContentWrap>
    <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="-mb-15px" label-width="68px">
      <el-form-item label="菜单名称" prop="catName">
        <el-input v-model="queryParams.catName" class="!w-240px" clearable placeholder="请输入商品名称"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="模板类型" prop="modeType">
        <el-select v-model="queryParams.modeType" class="!w-240px" clearable placeholder="请选择类型">
          <el-option v-for="dict in modeList" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
        <el-button v-hasPermi="['system:menu:create']" plain type="primary" @click="openForm('create', 0)">
          <Icon class="mr-5px" icon="ep:plus" />
          新增
        </el-button>
        <el-button plain type="danger" @click="toggleExpandAll">
          <Icon class="mr-5px" icon="ep:sort" />
          展开/折叠
        </el-button>
        <el-button plain @click="refreshMenu">
          <Icon class="mr-5px" icon="ep:refresh" />
          刷新菜单缓存
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-if="refreshTable" v-loading="loading" :data="list" :default-expand-all="isExpandAll" row-key="id"
      :show-overflow-tooltip="true">
      <el-table-column :show-overflow-tooltip="true" label="分类名称" prop="catName" width="250" />
      <el-table-column align="center" label="图标地址" prop="icon" width="150" />
      <el-table-column align="center" label="排序" prop="sort" width="60" />
      <el-table-column align="center" label="是否显示" prop="showFlag">
        <template #default="{ row }">
          {{ row.showFlag === 1 ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="模板类型" prop="modeType" width="150" />
      <el-table-column align="center" label="操作">
        <template #default="scope">
          <el-button v-hasPermi="['system:menu:update']" link type="primary" @click="openForm('update', scope.row)">
            修改
          </el-button>
          <el-button v-hasPermi="['system:menu:create']" link type="primary"
            @click="openForm('createLitle', scope.row)">
            新增
          </el-button>
          <el-button v-hasPermi="['system:menu:delete']" link type="danger" @click="handleDelete(scope.row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form :model="formData" :rules="formRules" label-width="100px">
      <el-form-item label="分类名称" prop="catName  ">
        <el-input v-model="formData.catName" clearable placeholder="请输入分类名称" />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="formData.sort" clearable placeholder="请输入排序" />
      </el-form-item>
      <el-form-item label="图标" prop="icon">
        <UploadImg v-model="formData.icon" />
      </el-form-item>
      <el-form-item label="显示状态" prop="showFlag">
        <el-radio-group v-model="formData.showFlag">
          <el-radio key="true" :label="1" border>显示</el-radio>
          <el-radio key="false" :label="0" border>隐藏</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="商品类型" prop="modeType">
        <el-select v-model="formData.modeType" class="!w-240px" clearable placeholder="请选择商品类型">
          <el-option v-for="dict in modeList" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { handleTree } from '@/utils/tree'
import { goodsCategoryApi } from '@/api/shops/goods-category'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'

defineOptions({ name: 'SystemMenu' })

const { wsCache } = useCache()
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const dialogVisible = ref(false)
const dialogTitle = ref('') // 弹窗的标题

const loading = ref(true) // 列表的加载中
const list = ref<any>([]) // 列表的数据
const modeList = ref<any>([])
const queryParams = reactive({
  pageNo: 1,
  pageSize: 100,
  catName: undefined,
  modeType: undefined
})
const formData = ref({
  id: undefined,
  parentId: Number(undefined),
  catName: undefined,
  sort: undefined,
  modeType: undefined,
  icon: undefined,
  showFlag: Number(undefined)
})
const formRules = reactive({
  catName: [{ required: true, message: '菜单名称不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '菜单顺序不能为空', trigger: 'blur' }],
  modeType: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
  showFlag: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
})
const queryFormRef = ref() // 搜索的表单
const isExpandAll = ref(false) // 是否展开，默认全部折叠
const refreshTable = ref(true) // 重新渲染表格状态

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const mode = await goodsCategoryApi.getModeList()
    modeList.value = mode
    const data = await goodsCategoryApi.getGoodsCategoryPage(queryParams)
    const datalist = data.list.filter((item: any) => {
      mode.filter((cos: any) => {
        item.modeType = item.modeType === cos.value ? cos.label : item.modeType
        return item
      })
      return item
    })
    list.value = handleTree(datalist)
  } finally {
    loading.value = false
  }
}
// 表单提交事件
const submitForm = async () => {
  if (!formRef) return
  if (dialogTitle.value === '新增') {
    await goodsCategoryApi.createGoodsCategory(formData.value)
    message.success(t('common.createSuccess'))
    dialogVisible.value = false
    await getList()
  }
  if (dialogTitle.value === '编辑') {
    await goodsCategoryApi.updateGoodsCategory(formData.value)
    message.success(t('common.updateSuccess'))
    dialogVisible.value = false
    await getList()
  }
}
/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, data: any) => {
  dialogVisible.value = true
  if (type === 'update') {
    dialogTitle.value = t('action.' + type)
    formData.value = data
  }
  if (type === 'create') {
    dialogTitle.value = t('action.' + type)
    formData.value.parentId = 0
    formData.value.catName = undefined,
      formData.value.sort = undefined,
      formData.value.modeType = undefined,
      formData.value.icon = undefined,
      formData.value.showFlag = Number(undefined)
  }
  if (type === 'createLitle') {
    dialogTitle.value = '新增'
    formData.value.parentId = data.id
    formData.value.catName = undefined,
      formData.value.sort = undefined,
      formData.value.modeType = undefined,
      formData.value.icon = undefined,
      formData.value.showFlag = Number(undefined)
  }
}

/** 展开/折叠操作 */
const toggleExpandAll = () => {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  nextTick(() => {
    refreshTable.value = true
  })
}

/** 刷新菜单缓存按钮操作 */
const refreshMenu = async () => {
  try {
    await message.confirm('即将更新缓存刷新浏览器！', '刷新菜单缓存')
    // 清空，从而触发刷新
    wsCache.delete(CACHE_KEY.USER)
    wsCache.delete(CACHE_KEY.ROLE_ROUTERS)
    // 刷新浏览器
    location.reload()
  } catch { }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await goodsCategoryApi.deleteGoodsCategory(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
